<!-- components/account/PhoneSettings.vue -->
<template>
  <div class="phone-settings">
    <div class="current-phone">
      <h4>当前绑定手机</h4>
      <p class="phone-number">{{ currentPhone }}</p>
    </div>

    <el-divider />

    <div class="change-phone">
      <h4>更换手机号</h4>
      <el-form :model="form" label-width="100px" style="max-width: 500px;">
        <el-form-item label="新手机号">
          <el-input v-model="form.newPhone" placeholder="请输入新手机号码" />
        </el-form-item>

        <el-form-item label="验证码">
          <div class="captcha-input">
            <el-input v-model="form.captcha" placeholder="请输入验证码" style="width: 200px;" />
            <el-button
                :disabled="countdown > 0"
                @click="sendCaptcha"
                style="margin-left: 10px;"
            >
              {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">确认更换</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

// 定义props接口
interface Props {
  phone?: string
}

// 接收父组件传递的phone属性
const props = withDefaults(defineProps<Props>(), {
  phone: '--'
})
const currentPhone = ref(props.phone)
const form = reactive({
  newPhone: '',
  captcha: ''
})
const countdown = ref(0)

// 监听props.phone的变化
watch(() => props.phone, (newPhone) => {
  currentPhone.value = newPhone
})

const sendCaptcha = () => {
  if (!form.newPhone) {
    ElMessage.warning('请输入手机号码')
    return
  }

  // 模拟发送验证码
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)

  ElMessage.success('验证码已发送')
}

const handleSubmit = () => {
  if (!form.newPhone || !form.captcha) {
    ElMessage.warning('请填写完整信息')
    return
  }

  // 模拟更换手机号
  currentPhone.value = form.newPhone
  form.newPhone = ''
  form.captcha = ''
  ElMessage.success('手机号更换成功')

  // 如果需要，可以在这里触发事件通知父组件
  // emit('phone-updated', currentPhone.value)
}
</script>

<style scoped>
.phone-settings {
  padding: 20px;
}

.current-phone h4,
.change-phone h4 {
  margin-bottom: 16px;
  color: #303133;
  font-weight: 600;
}

.phone-number {
  font-size: 18px;
  color: #409EFF;
  font-weight: 500;
}

.captcha-input {
  display: flex;
  align-items: center;
}
</style>
